const express = require('express');
const app = express();
const mysql = require('mysql');

//连接数据库
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'txy020308',
    database: 'movie',
    port: '3306'
});
connection.connect();


//解决跨域请求
app.all('*',function(req,res,next){
    res.header("Access-Control-Allow-Origin","*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

//hotmovie
app.get('/hotmovie',function(err,res){
    const sql = 'select * from hotmovie'; 
    connection.query(sql,function(err,result){
        if(err){
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        // result内放的就是返回的数据，res是api传数据
        // 返回的数据需要转换成JSON格式
        res.json(result); 
    });
});
//expecetedmovies
app.get('/expectedmovies',function(err,res){
    const sql = 'select * from expectedmovies'; 
    connection.query(sql,function(err,result){
        if(err){
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        // result内放的就是返回的数据，res是api传数据
        // 返回的数据需要转换成JSON格式
        res.json(result); 
    });
});
//moviedetail
app.get('/moviedetail/:id',function(req,res){
    let id = req.params["id"];
    const sql = 'select * from moviedetail where id=?';
    connection.query(sql,id,function(err,result){
        if(err){
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        // result内放的就是返回的数据，res是api传数据
        // 返回的数据需要转换成JSON格式
        res.json(result); 
    });
});
//comingMovie
app.get('/comingmovies',function(req,res){
    const sql = 'select * from comingmovies';
    connection.query(sql,function(err,result){
        if(err){
            console.log('[SELECT ERROR] - ', err.message);
            return;
        }
        // result内放的就是返回的数据，res是api传数据
        // 返回的数据需要转换成JSON格式
        res.json(result); 
    });
});

var server = app.listen(8081, '127.0.0.1', function () {

    var host = server.address().address;
    var port = server.address().port;

    console.log("地址为 http://%s:%s", host, port);
}) 